package com.example.csetpp.utils;


import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyuncs.auth.StaticCredentialsProvider;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 * 因为不属于controller层，也不属于service层，所以用component注解来存放到IOC容器里
 */
@Component
public class AliOSSUtils {

    private String endpoint = "https://oss-cn-guangzhou.aliyuncs.com";
    private String accessKeyId = "LTAI5t8kZuNvieBykEjVuA3G";
    private String accessKeySecret = "wS5m8iQPZgZDXS2BqgmQmD2LIOCAsu";
    private String bucketName = "predict-bucket2";

    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile file) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        // 创建ObjectMetadata对象并设置Content-Type
        ObjectMetadata metadata = new ObjectMetadata();

        // 根据文件扩展名设置对应的Content-Type
        String contentType = getContentType(fileName.substring(fileName.lastIndexOf(".")));
        metadata.setContentType(contentType);

        // 上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream, metadata);

        // 文件访问路径
        String url = "http://hanxi.cyou/" + fileName;

        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }


    //0-文件名，1-路径名
    public  void deleteFile(String objectName,Integer type) throws Exception {
            String aimName = objectName;
            if(type == 0){
                aimName = objectName;
            } else if(type ==1){
                aimName = objectName.substring(objectName.lastIndexOf("/")+1);
            }

            // 填写文件完整路径。文件完整路径中不能包含Bucket名称。
//            String objectName = "exampleobject.txt";
            // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-hangzhou。
            String region = "cn-guangzhou";

            // 创建OSSClient实例。
            // 当OSSClient实例不再使用时，调用shutdown方法以释放资源。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//            OSS ossClient = OSSClientBuilder.create()
//                    .endpoint(endpoint)
//                    .credentialsProvider(credentialsProvider)
//                    .clientConfiguration(clientBuilderConfiguration)
//                    .region(region)
//                    .build(accessKeyId,accessKeySecret);

            try {
                // 删除文件或目录。如果要删除目录，目录必须为空。
                ossClient.deleteObject(bucketName, aimName);
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }


    // 根据文件扩展名获取对应的Content-Type
    private String getContentType(String fileExtension) {
        switch (fileExtension.toLowerCase()) {
            case ".jpg":
            case ".jpeg":
                return "image/jpeg";
            case ".png":
                return "image/png";
            case ".gif":
                return "image/gif";
            case ".pdf":
                return "application/pdf";
            case ".txt":
                return "text/plain";
            case ".html":
                return "text/html";
            case ".mp4":
                return "video/mp4";
            case ".doc":
                return "application/msword";
            case ".docx":
                return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            case ".xls":
                return "application/vnd.ms-excel";
            case ".xlsx":
                return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            case ".ppt":
                return "application/vnd.ms-powerpoint";
            case ".pptx":
                return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
            case ".json":
                return "application/json";
            case ".csv":
                return "text/csv";
            default:
                return "application/octet-stream";
        }
    }

}
